package com.ncss.http.proxy.server.handler;

import com.ncss.http.proxy.server.CloseUtils;
import com.ncss.http.proxy.server.Parameters;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpClientHandler implements Runnable {


    private Socket socket;

    public HttpClientHandler(Socket socket) {
        this.socket = socket;
    }

    private void handler() {
        try {
            BufferedReader bd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            /**
             * 接受HTTP请求
             */
            String requestHeader;
            int contentLength = 0;
            Parameters parameters = null;
            Map<String, String> headers = new HashMap<String, String>();
            while ((requestHeader = bd.readLine()) != null && !requestHeader.isEmpty()) {
                System.out.println(requestHeader);
                /**
                 * 获得GET参数
                 */
                if (requestHeader.startsWith("GET")) {
                    int begin = requestHeader.indexOf("/") + 1;
                    int end = requestHeader.indexOf("HTTP/");
                    String condition = requestHeader.substring(begin, end);
                    System.out.println("GET参数是：" + condition);
                    String[] args = condition.split("/");
                    if (args.length == 3) {
                        parameters = new Parameters(args[0].trim(), args[1].trim(), args[2].trim());
                        parameters.setUrl("https://tiles.windy.com/tiles/v8.1/darkmap/{z}/{x}/{y}.png");
                        parameters.setFilePath("D:\\darkmap");

                    }
                } else {
                    int i = requestHeader.indexOf(":");
                    headers.put(requestHeader.substring(0, i), requestHeader.substring(i + 1));
                }

            }
            if (parameters != null) {
                CacheImageHandler handler = new CacheImageHandler(parameters);
                File file = handler.handle();
                response(file);
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    public void response(File file) {
        InputStream in = null;
        OutputStream out = null;

        try {
            //发送回执
            out = socket.getOutputStream();

            PrintWriter pw = new PrintWriter(out);
            if (null == file) {

                pw.println("HTTP/1.1 404 OK");
                pw.println("Content-type:text/html");
                pw.println();
                pw.println("<h1>not found..</h1>");

                pw.flush();
            } else {
                pw.println("HTTP/1.1 200 OK");
                pw.println("Content-type:image/png");
                pw.println();
                pw.flush();
                in = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(in, out, socket);
        }
    }

    @Override
    public void run() {
        this.handler();
    }
}
